<template>
  <div class="register-container">
    <div class="card">
      <h2>用户注册</h2>
      <form @submit.prevent="handleRegister">
        <!-- 用户名 -->
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            v-model="form.username" 
            required
            placeholder="请输入用户名"
            @blur="checkUsername"
            :class="{ 'error': usernameError }"
          >
          <div v-if="usernameError" class="error-message">{{ usernameError }}</div>
          <div v-if="usernameChecking" class="checking-message">检查中...</div>
        </div>

        <!-- 密码 -->
        <div class="form-group">
          <label>密码</label>
          <input 
            type="password" 
            v-model="form.password" 
            required
            placeholder="请输入6-10位密码"
            @input="validatePassword"
            :class="{ 'error': passwordError }"
          >
          <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
        </div>

        <!-- 确认密码 -->
        <div class="form-group">
          <label>确认密码</label>
          <input 
            type="password" 
            v-model="form.confirmPassword" 
            required
            placeholder="请再次输入密码"
            @input="validateConfirmPassword"
            :class="{ 'error': confirmPasswordError }"
          >
          <div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>
        </div>

        <!-- 电话号码 -->
        <div class="form-group">
          <label>电话号码</label>
          <input 
            type="text" 
            v-model="form.phone" 
            required
            placeholder="请输入11位手机号码"
            @input="validatePhone"
            :class="{ 'error': phoneError }"
          >
          <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
        </div>

        <!-- 验证码 -->
        <div class="form-group">
          <label>验证码</label>
          <div class="verification-code-group">
            <input 
              type="text" 
              v-model="form.verificationCode" 
              required
              placeholder="请输入6位验证码"
              maxlength="6"
              :class="{ 'error': verificationCodeError }"
            >
            <button 
              type="button" 
              class="send-code-btn"
              :disabled="!canSendCode || countdown > 0"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s后重新发送` : '发送验证码' }}
            </button>
          </div>
          <div v-if="verificationCodeError" class="error-message">{{ verificationCodeError }}</div>
        </div>

        <button 
          type="submit" 
          class="submit-btn"
          :disabled="!formValid"
        >
          提交注册
        </button>
        
        <p class="link-text">
          已有账号？<router-link to="/user/login">去登录</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const router = useRouter()

const form = ref({
  username: '',
  password: '',
  confirmPassword: '', // 新增确认密码字段
  phone: '',
  verificationCode: ''
})

const errors = ref({
  username: '',
  password: '',
  confirmPassword: '', // 新增确认密码错误字段
  phone: '',
  verificationCode: ''
})

const usernameChecking = ref(false)
const countdown = ref(0)

// 计算属性
const canSendCode = computed(() => {
  return form.value.phone && !phoneError.value && countdown.value === 0
})

const formValid = computed(() => {
  return form.value.username && 
         form.value.password && 
         form.value.confirmPassword && // 新增确认密码检查
         form.value.phone && 
         form.value.verificationCode &&
         !errors.value.username &&
         !errors.value.password &&
         !errors.value.confirmPassword && // 新增确认密码错误检查
         !errors.value.phone &&
         !errors.value.verificationCode
})

// 错误信息
const usernameError = computed(() => errors.value.username)
const passwordError = computed(() => errors.value.password)
const confirmPasswordError = computed(() => errors.value.confirmPassword) // 新增确认密码错误
const phoneError = computed(() => errors.value.phone)
const verificationCodeError = computed(() => errors.value.verificationCode)

// 监听密码变化，自动验证确认密码
watch(() => form.value.password, () => {
  if (form.value.confirmPassword) {
    validateConfirmPassword()
  }
})

// 监听确认密码变化，清除错误
watch(() => form.value.confirmPassword, () => {
  if (errors.value.confirmPassword && form.value.password === form.value.confirmPassword) {
    errors.value.confirmPassword = ''
  }
})

// 检查用户名是否重复
const checkUsername = async () => {
  if (!form.value.username) {
    errors.value.username = '用户名不能为空'
    return
  }

  if (form.value.username.length < 3) {
    errors.value.username = '用户名至少3位'
    return
  }

  usernameChecking.value = true
  try {
    const response = await request.get('/user/register/isExist', {
      params: {
        username: form.value.username
      }
    })
    
    if (response.code == 500) {
      errors.value.username = response.message
    } 
  } catch (error) {
    console.error('检查用户名失败', error)
    errors.value.username = '检查用户名时出错'
  } finally {
    usernameChecking.value = false
  }
}

// 验证密码
const validatePassword = () => {
  if (!form.value.password) {
    errors.value.password = '密码不能为空'
    return
  }

  if (form.value.password.length < 6) {
    errors.value.password = '密码至少6位'
    return
  }

  if (form.value.password.length > 10) {
    errors.value.password = '密码最多10位'
    return
  }

  // 可以添加更复杂的密码规则
  if (!/^(?=.*[a-zA-Z])(?=.*\d).{6,10}$/.test(form.value.password)) {
    errors.value.password = '密码必须包含字母和数字'
    return
  }

  errors.value.password = ''
  
  // 密码验证通过后，如果确认密码已输入，重新验证确认密码
  if (form.value.confirmPassword) {
    validateConfirmPassword()
  }
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!form.value.confirmPassword) {
    errors.value.confirmPassword = '请确认密码'
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    return
  }

  errors.value.confirmPassword = ''
}

// 验证电话号码
const validatePhone = () => {
  if (!form.value.phone) {
    errors.value.phone = '电话号码不能为空'
    return
  }

  if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
    errors.value.phone = '请输入正确的11位手机号码'
    return
  }

  errors.value.phone = ''
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return

  try {
    await request.post('/user/register/send', {
      phone: form.value.phone
    })
    
    // 开始倒计时
    countdown.value = 120
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败', error)
    ElMessage.error('发送验证码失败，请重试')
  }
}

// 处理注册
const handleRegister = async () => {
  // 再次验证所有字段
  validatePassword()
  validateConfirmPassword() // 新增确认密码验证
  validatePhone()

  if (!form.value.verificationCode) {
    errors.value.verificationCode = '请输入验证码'
    return
  }

  if (!/^\d{6}$/.test(form.value.verificationCode)) {
    errors.value.verificationCode = '验证码必须是6位数字'
    return
  }

  if (!formValid.value) {
    ElMessage.warning('请完善注册信息')
    return
  }

  try {
    // 注册时只发送必要的字段，不发送确认密码
    const registerData = {
      username: form.value.username,
      password: form.value.password,
      phone: form.value.phone,
      verificationCode: form.value.verificationCode
    }
    
    const res = await request.post('/user/register', registerData)
    if(res.code == 500) {
      ElMessage.error('注册失败，请重试')
    } else {
      ElMessage.success('注册成功，请等待审核')
      router.push('/user/login')
    }
  } catch(error) {
    console.error('注册失败', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('注册失败，请重试')
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f5f5f5;
}
.card {
  width: 400px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.form-group {
  margin-bottom: 1.5rem;
  position: relative;
}
.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}
input {
  width: 95%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}
input:focus {
  outline: none;
  border-color: #3B82F6;
}
input.error {
  border-color: #ff4d4f;
}
.error-message {
  color: #ff4d4f;
  font-size: 0.8rem;
  margin-top: 0.3rem;
}
.checking-message {
  color: #1890ff;
  font-size: 0.8rem;
  margin-top: 0.3rem;
}
.verification-code-group {
  display: flex;
  gap: 0.5rem;
}
.verification-code-group input {
  flex: 1;
}
.send-code-btn {
  padding: 0.8rem 1rem;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  min-width: 120px;
}
.send-code-btn:disabled {
  background-color: #e9ecef;
  cursor: not-allowed;
  color: #999;
}
.send-code-btn:not(:disabled):hover {
  background-color: #e9ecef;
}
.submit-btn {
  width: 100%;
  padding: 0.8rem;
  background: #3B82F6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}
.submit-btn:hover:not(:disabled) {
  background: #2563EB;
}
.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
.link-text {
  text-align: center;
  margin-top: 1rem;
  color: #666;
}
.link-text a {
  color: #3B82F6;
  text-decoration: none;
}
.link-text a:hover {
  text-decoration: underline;
}
</style>